package com.csair.seam.controller.index;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csair.seam.domain.model.entity.Equip;
import com.csair.seam.domain.model.entity.SysUser;
import com.csair.seam.domain.model.entity.Visits;
import com.csair.seam.domain.service.IEquipService;
import com.csair.seam.domain.service.ISysUserService;
import com.csair.seam.domain.service.IVisitsService;
import com.csair.seam.infrastructure.config.DictionaryConfigurationProperties;
import com.csair.seam.infrastructure.ehome.EhomeParamData;
import com.csair.seam.infrastructure.log.LoginLogInfo;
import com.csair.seam.infrastructure.utils.DateHelper;
import com.csair.seam.infrastructure.utils.JwtUtil;
import com.csair.seam.infrastructure.web.BaseController;
import com.csair.seam.infrastructure.web.BaseResponse;
import com.csair.seam.infrastructure.web.ResponseCode;
import com.csair.seam.infrastructure.web.user.UserInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "基础公共服务")
@Controller
@Slf4j
public class IndexController extends BaseController {
	
	@Autowired
    private ISysUserService userService;
	
	@Autowired
    private IEquipService equipService;
	
	@Autowired
	private IVisitsService visitsService;
	
	@Autowired
	private DictionaryConfigurationProperties dictionaryConfigurationProperties;
	
	@GetMapping("/login")
    @ApiOperation(value = "SSO登录", notes = "SSO登录成功后跳转returnUrl",httpMethod="GET")
	@ApiIgnore
	@SuppressWarnings("all")
    public String toReturnUrl(){
		return "redirect:"+dictionaryConfigurationProperties.getFontendAddress();
    }
	
    @ApiOperation(value = "获取登录用户信息", notes = "getCurrentUser",httpMethod="GET")
    @GetMapping(value="/current")
    @ResponseBody
    @SuppressWarnings("all")
    public BaseResponse<UserInfo> getCurrentUser(){
		SysUser sysUser = userService.queryUserByAccount(getAccount());
		UserInfo userInfo = new UserInfo(sysUser);
		setEquipInfo(userInfo);
		userInfo.setAdmin(StringUtils.contains(dictionaryConfigurationProperties.getAdminList(), sysUser.getAccount()));
		
		getVisitsCount(userInfo);
		log.info("【用户登录】：{}",JSON.toJSONString(new LoginLogInfo(DateHelper.getCurrentDateTimeStr(), getIpAddress(), sysUser.getAccount())));
		return buildSuccess(userInfo);
    }
    
    @ApiOperation(value = "E家登录", notes = "getEhomeUser",httpMethod="POST")
    @ApiIgnore
    @PostMapping(value="/ehome")
    @ResponseBody
    public BaseResponse<UserInfo> getEhomeUser(EhomeParamData param){
		if(param == null || StringUtils.isEmpty(param.getLoginAccount()) || StringUtils.isEmpty(param.getToken())||StringUtils.isEmpty(param.getDevice())) {
			return new BaseResponse<>(ResponseCode.PARAM_ERROR,"参数错误",null);
		}
		
		UserInfo userInfo = userService.checkUserInfo(param);
		setEquipInfo(userInfo);
		
		//JWT token
		String jwtToken = JwtUtil.createTokenwithClaim(userInfo.getAccount());
		userInfo.setToken(jwtToken);
		
		getVisitsCount(userInfo);
		
		log.info("【用户E家登录】：{}",JSON.toJSONString(new LoginLogInfo(DateHelper.getCurrentDateTimeStr(), getIpAddress(), userInfo.getAccount())));
        return  buildSuccess(userInfo);
    }
    
	@ApiOperation(value = "健康测试页", httpMethod = "GET")
	@ApiIgnore
	@RequestMapping(value = "/health")
	@ResponseBody
	@SuppressWarnings("all")
	public String health() {
		try {
			return "<Result><Success>True</Success><Detail></Detail></Result>";
		} catch (Exception ex) {
			return "<Result><Success>False</Success><Detail>数据库连接异常:</Detail></Result>";
		}
	}
	
	private void setEquipInfo(UserInfo userInfo) {
		Equip equip = equipService.findMyEquipInfo(userInfo.getAccount());
		if(equip != null) {
			userInfo.setEquipNum(equip.getOriginValue().intValue());
			userInfo.setEquipPrice(equip.getPurcPrice());
		}
	}
	
	private void getVisitsCount(UserInfo userInfo) {
		int totalUv = visitsService.count();
		userInfo.setTotalUv(totalUv);
		
		Visits visits = new Visits();
		visits.setVisitTime(DateHelper.getCurrentDateStr());
		QueryWrapper<Visits> queryWrapper = new QueryWrapper<>(visits);
		int todayUv = visitsService.count(queryWrapper);
		userInfo.setTodayUv(todayUv);
	}
}

